﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MyMeta;
using Liger.Generate; 

public partial class _Code : System.Web.UI.Page
{
    public static dbDriver GetDbDriver(string dbType)
    {
        switch (dbType.ToLower())
        {
            case "access":
                return dbDriver.Access;
            default:
                return dbDriver.SQL;
        }
    }
    private string DbType { get { return Request["dbType"]; } }

    private string ConnectionString { get { return Request["connectionString"]; } }

    private string Table { get { return Request["table"]; } }

    private string View { get { return Request["view"]; } }

    private bool IsView
    {
        get
        {
            return !string.IsNullOrEmpty(View);
        }
    }

    private string Namespace
    {
        get
        {
            if (string.IsNullOrEmpty(Request["Namespace"])) return "Liger.Model";
            return Request["Namespace"];
        }
    }

    private ViewBase GetView()
    {
        var root = new MyMeta.dbRoot();
        root.Connect(GetDbDriver(this.DbType), this.ConnectionString);
        if (root.IsConnected)
        {
            var views = root.DefaultDatabase.Views;
            foreach (IView view in views)
            {
                if (string.Compare(View, view.Name, true) == 0)
                {
                    return new ViewBase(view);
                }
            }
        }
        return null;
    } 
    private TableBase GetTable()
    {
        var root = new MyMeta.dbRoot();  
        root.Connect(GetDbDriver(this.DbType), this.ConnectionString);
        if (root.IsConnected)
        {
            var tables = root.DefaultDatabase.Tables; 
            foreach (ITable table in tables)
            {
                if (string.Compare(Table, table.Name, true) == 0)
                {
                    return new TableBase(table);
                }
            }
        }
        return null;
    } 
    protected string code = "";
    protected void Page_Load(object sender, EventArgs e)
    {
         
        var helper = new NVelocityHelper(Server.MapPath("~/Template/"), "entity.vtl");
        if (IsView)
        {
            helper.Add("Table",GetView());
        }
        else
        {
            helper.Add("Table", GetTable());
        }
        helper.Add("Copyright", false);
        helper.Add("Namespace", Namespace);
        code = helper.Output();
    }
}